package com.tronsis.distribution.activity.me;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.tronsis.distribution.R;
import com.tronsis.distribution.SysApplication;
import com.tronsis.distribution.bean.RegionBean;
import com.tronsis.distribution.bean.RegionHistoryBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.widget.address.BottomDialog;
import com.tronsis.distribution.widget.address.OnAddressSelectedListener;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Allen：归属地选择
 */
public class RegionActivity extends ToolBarBaseActivity {
    @BindView(R.id.rv_region)
    RecyclerView rvRegion;
    private CommonAdapter<RegionHistoryBean> mAdapter;
    private List<RegionHistoryBean> regionHistorys = new ArrayList<>();
    private RegionHistoryBean lastRegionHistoryBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_region);
        ButterKnife.bind(this);
        setTitle(true, "归属地");
        setRightTvText("确定");
        initView();
        getRegionHistory();
    }

    private void initView() {
        mAdapter = new CommonAdapter<RegionHistoryBean>(mContext, regionHistorys, R.layout.item_region) {
            @Override
            protected void convert(final ViewHolder holder, final RegionHistoryBean regionHistoryBean, final int position) {
                holder.setText(R.id.tv_region, CommonUtil.getRegionString(regionHistoryBean.k));
                holder.setText(R.id.tv_contribute, regionHistoryBean.v + "");
                if (regionHistoryBean.isCheckd) {
                    holder.setImageResource(R.id.iv_check, R.drawable.ic_select_circle);
                } else {
                    holder.setImageResource(R.id.iv_check, R.drawable.ic_empty_circle);
                }
                holder.setOnClickListener(R.id.iv_check, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int adapterPosition = holder.getAdapterPosition();
                        if (!regionHistoryBean.isCheckd) {
                            for (int i = 0; i < regionHistorys.size(); i++) {
                                if (adapterPosition == i) {
                                    regionHistorys.get(i).isCheckd = true;
                                    lastRegionHistoryBean = regionHistorys.get(i);
                                } else {
                                    regionHistorys.get(i).isCheckd = false;
                                }
                            }
                            notifyDataSetChanged();
                        }
                    }
                });


            }

        };

        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = getResources().getColor(R.color.line_white);
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        rvRegion.addItemDecoration(decoration);
        rvRegion.setLayoutManager(new LinearLayoutManager(mContext));
        rvRegion.setAdapter(mAdapter);
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:
                httpUpdateUserRegion(lastRegionHistoryBean.k);
                break;
            case LEFT_BUTTON:

                break;
        }
    }

    @OnClick(R.id.btn_add)
    public void onViewClicked() {
        showRegionPop();
    }

    private void getRegionHistory() {
        try {
            UserBizFactory.createBiz().getRegionHistory(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    List<RegionHistoryBean> datas = (List<RegionHistoryBean>) data;
                    lastRegionHistoryBean = datas.get(0);
                    lastRegionHistoryBean.isCheckd = true;
                    regionHistorys.clear();
                    regionHistorys.addAll(datas);
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showRegionPop() {
        UserBean userBean = UserBizFactory.createBiz().getLoginUser(mContext);
        String level = userBean.getLevel();

        List<RegionBean> regionBeanList = SysApplication.getRegionList();
        final RegionBean regionBean = new RegionBean();
        regionBean.setChildren(regionBeanList);

        int regionLevel = 3;
        switch (level) {
            case "B":
                regionLevel = 1;
                break;
            case "C":
                regionLevel = 2;
                break;
            case "D":
            case "E":
                regionLevel = 3;
                break;
        }

        final BottomDialog dialog = new BottomDialog(this, regionBean, regionLevel);
        final int finalRegionLevel = regionLevel;
        dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(RegionBean province, RegionBean city, RegionBean county, RegionBean street) {
                String s = (province == null ? "" : "" + province.getName())
                        + (city == null ? "" : "" + city.getName())
                        + (county == null ? "" : "" + county.getName())
                        + (street == null ? "" : "" + street.getName());
                String mRegion = null;
                switch (finalRegionLevel) {
                    case 1:
                        mRegion = province.getCode();
                        break;
                    case 2:
                        mRegion = city.getCode();
                        break;
                    case 3:
                        mRegion = county.getCode();
                        break;
                }
                dialog.dismiss();
                httpUpdateUserRegion(mRegion);
            }
        });
        dialog.show();
        dialog.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void httpUpdateUserRegion(String region) {
        if (region.length() < 6) {
            StringBuilder regionBuilder = new StringBuilder(region);
            for (int i = 0; i < (6 - region.length()); i++) {
                regionBuilder.append("0");
            }
            region = regionBuilder.toString();
        }
        try {
            final UserBean userBean = UserBizFactory.createBiz().getLoginUser(mContext);
            final String finalRegion = region;
            UserBizFactory.createBiz().updateInfo(this, userBean.isAppNotice(), null, null, null, null, null, null, region, null, null, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    userBean.setRegion(finalRegion);
                    DBUtil.getInstance(mContext).update(userBean);
                    getRegionHistory();
                    EventBus.getDefault().post(new EventMessage(EventTag.MY_REGION, finalRegion));
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

}
